<template>
  <div class="word-select">
    <el-dialog
      :title="title"
      :visible.sync="visible"
      :width="dialogWidth"
      :before-close="handleBeforeClose"
      destroy-on-close
      :show-close="false"
      center
      @close="handleCancel"
    >
      <!-- 搜索筛选区域 -->
      <div class="search-bar">
        <!-- 分类切换 -->
        <el-radio-group v-model="selectedCategory" class="category-group" @change="handleCategoryChange">
          <el-radio-button label="sys">官方词库</el-radio-button>
          <el-radio-button label="me">我的词库</el-radio-button>
          <el-radio-button label="stu">学生词库</el-radio-button>
        </el-radio-group>

        <!-- 搜索框 -->
        <div class="search-input-group">
          <el-select
            v-model="selectedBookTypeValue"
            placeholder="请选择教材版本"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
          <el-input
            v-model="keyword"
            placeholder="输入词库名称搜索"
            clearable
            size="small"
            class="search-input"
            @clear="handleSearch"
            @keydown.enter.native="handleSearch"
          />
          <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
        </div>
      </div>

      <!-- 词库列表区域 -->
      <div class="library-list">
        <!-- 空状态 -->
        <el-empty
          v-if="!loading && libraryList.length === 0"
          description="暂无匹配的词库数据"
          class="empty-state"
        />

        <!-- 加载中 -->
        <div v-if="loading" class="loading-state">
          <span class="loading-text">加载中...</span>
        </div>

        <!-- 词库卡片列表 -->
        <div v-else>
          <div v-for="(type,index) in libraryList" :key="index" class="card-body">
            <span>{{ type.parentLabel }}</span>
            <div class="card-grid">
              <div
                v-for="(item, index) in type.children"
                :key="item.id"
                class="library-card"
                :class="{ 'card-selected': selectedIds.includes(item.id) }"
                @click="handleCardClick(item)"
              >
                <!-- 卡片内容 -->
                <div class="card-content">
                  <!-- 封面图 -->
                  <div class="card-cover">
                    <img src="@/assets/bookCover.png" alt="词库封面" class="cover-img">
                    <!-- 开通状态标签 -->
                    <el-tag
                      :type="selectedIdsWait.includes(item.id) ? 'warning' :selectedIds.includes(item.id) ? 'success' : 'info'"
                      size="mini"
                      class="status-tag"
                    >
                      {{
                        selectedIdsWait.includes(item.id) ? '待确认' : selectedIds.includes(item.id) ? '已开通' : '未开通'
                      }}
                    </el-tag>
                  </div>

                  <!-- 词库信息 -->
                  <div class="card-info">
                    <h3 class="library-name" :title="item.label">{{ item.label }}</h3>
                    <div class="info-row">
                      <span class="info-item"><i class="el-icon-document"/> {{ item.wordNum }} 单词</span>
                      <span class="info-item"><i class="el-icon-user"/> {{ item.studyTotal }} 人学过</span>
                    </div>
                    <div class="info-row">
                      <span class="info-item info-item-last" @click.stop="handleOpenLibrary(item)"><i
                        class="fa-solid fa-list-ul"
                      />词表</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>

      <!-- 分页区域 -->
      <div v-if="total > 0 && !loading" class="pagination-bar">
        <el-pagination
          small
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30,50,100]"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 底部操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" :disabled="selectedIds.length === 0" @click="handleConfirm">
          确认选择 ({{ selectedIds.length }})
        </el-button>
      </div>
    </el-dialog>

    <word-dialog v-model="libraryVisible" :lib-id="currentLibId"/>
  </div>
</template>

<script>
import { queryPage, stuOneQueryPage, sysRootTypeList } from '@/api/wordSystemLibraryType'
import WordDialog from '@/views/vocabulary/component/wordPage.vue'
import { lexiconActivation, openedList } from '@/api/wordSystemLibraryTypeStu' // 复用原接口

export default {
  name: 'WordLibrarySelectDialog',
  components: { WordDialog },
  props: {
    // 控制弹框显示/隐藏
    visible: {
      type: Boolean,
      default: false
    },
    // 弹框标题
    title: {
      type: String,
      default: '选择词库'
    },
    // 弹框宽度
    dialogWidth: {
      type: String,
      default: '80%'
    },
    // 初始学生id
    initStuId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 分类筛选： sys-官方, me-我的, stu-学生
      selectedCategory: 'sys',
      // 搜索关键词
      keyword: '',
      // 词库列表数据
      libraryList: [],
      // 总条数
      total: 0,
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      // 加载状态
      loading: false,
      // 选中的词库ID数组
      selectedIds: [],
      // 新选中的词库ID数组（包含取消的和添加的）
      selectedIdsWait: [],
      // 初始选中值
      initialSelectedIds: [],
      currentLibId: '',
      libraryVisible: false,
      typeOptions: [],
      selectedBookTypeValue: ''
    }
  },
  watch: {
    // 监听初始选中值变化，同步到selectedIds
    initialSelectedIds: {
      immediate: true,
      handler(newVal) {
        this.selectedIds = [...newVal]
      }
    }
  },
  mounted() {
    // 初始化加载数据
    this.loadLibraryData()
    // 获取开通的词库
    this.loadInitialSelectedIds()
    // 获取词库分类
    this.loadSysRootTypeList()
  },
  methods: {
    /**
     * 获取初始选中值
     * @returns {Promise<void>}
     */
    async loadInitialSelectedIds() {
      const res = await openedList({ stuId: this.initStuId })
      this.initialSelectedIds = res || []
    },
    async loadSysRootTypeList() {
      const res = await sysRootTypeList()
      this.typeOptions = res || []
    },
    /**
     * 加载词库数据
     */
    async loadLibraryData() {
      if (this.loading) return
      this.loading = true

      try {
        // 构造请求参数（分类为all时不传递attribution）
        const param = {
          keyword: this.keyword.trim(),
          parentId: this.selectedBookTypeValue
        }
        param.attribution = this.selectedCategory

        let res = {}

        if (this.selectedCategory === 'stu') {
          param.id = this.initStuId
          res = await stuOneQueryPage({
            page: {
              pageNum: this.currentPage,
              pageSize: this.pageSize
            },
            param
          })
        } else {
          res = await queryPage({
            page: {
              pageNum: this.currentPage,
              pageSize: this.pageSize
            },
            param
          })
        }
        this.libraryList = res?.records || []
        this.total = res?.total * 1 || 0
      } catch (error) {
        this.$message.error('加载词库数据失败，请重试')
        console.error('词库加载错误:', error)
      } finally {
        this.loading = false
      }
    },

    /**
     * 分类切换事件
     */
    handleCategoryChange() {
      this.currentPage = 1 // 重置页码
      this.loadLibraryData()
    },

    /**
     * 搜索事件
     */
    handleSearch() {
      this.currentPage = 1 // 重置页码
      this.loadLibraryData()
    },

    /**
     * 分页大小变化事件
     */
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1 // 重置页码
      this.loadLibraryData()
    },

    /**
     * 页码变化事件
     */
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.loadLibraryData()
    },

    /**
     * 卡片点击事件（选中/取消选中）
     */
    handleCardClick(item) {
      if (this.selectedIds.includes(item.id)) {
        // 取消选择
        this.selectedIds = this.selectedIds.filter(id => id !== item.id)
        // 初始选中存在 但是 当前选中不存在 则表示取消（标记为 待确认 状态）
        if (this.initialSelectedIds.includes(item.id) && !this.selectedIds.includes(item.id)) {
          // 待确认队列不存在 添加
          if (!this.selectedIdsWait.includes(item.id)) {
            this.selectedIdsWait.push(item.id)
          }
        } else if (!this.initialSelectedIds.includes(item.id) && !this.selectedIds.includes(item.id)) {
          // 初始选中不存在 但是 当前选中不存在 则表示取消（标记为 待确认 状态）
          this.selectedIdsWait = this.selectedIdsWait.filter(id => id !== item.id)
        }
      } else {
        // 选择
        this.selectedIds.push(item.id)

        // 初始选中不存在 但是 当前选中不存在 则表示取消（标记为 待确认 状态）
        if (!this.initialSelectedIds.includes(item.id) && this.selectedIds.includes(item.id)) {
          // 待确认队列不存在 添加
          if (!this.selectedIdsWait.includes(item.id)) {
            this.selectedIdsWait.push(item.id)
          }
        } else if (this.initialSelectedIds.includes(item.id) && this.selectedIds.includes(item.id)) {
          // 初始选中存在 但是 当前选中也存在 则表示未改动 待确认队列存在 删除
          this.selectedIdsWait = this.selectedIdsWait.filter(id => id !== item.id)
        }
      }
    },

    /**
     * 取消按钮事件
     */
    handleCancel() {
      this.$emit('update:visible', false)
      // 重置选中状态（可选）
      this.selectedIds = []
    },

    /**
     * 确认按钮事件
     */
    async handleConfirm() {
      // 触发父组件事件，传递选中的ID和完整数据
      const selectedData = {
        stuId: this.initStuId,
        libTypeIds: [...this.selectedIds]
      }
      await lexiconActivation(selectedData)
      this.$emit('update:visible', false)
      this.$notify({ type: 'success', message: '开通成功' })
    },

    /**
     * 弹框关闭前事件
     */
    handleBeforeClose(done) {
      done()
      // 重置状态（避免下次打开时保留上次数据）
      this.selectedCategory = 'sys'
      this.keyword = ''
      this.currentPage = 1
      this.selectedIds = []
    },

    handleOpenLibrary(item) {
      this.currentLibId = item.id
      this.libraryVisible = true
    }
  }
}
</script>

<style scoped lang="scss">
// 搜索筛选区域
.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  align-items: center;

  .category-group {
    flex-shrink: 0;
  }

  .search-input-group {
    display: flex;
    gap: 10px;
    flex-grow: 1;
    min-width: 300px;

    .search-input {
      ::v-deep .el-input__inner {
        height: 100%;
      }
    }
  }
}

// 词库列表区域
.library-list {
  max-height: 500px;
  overflow-y: auto;
  padding: 10px 0;

  .empty-state {
    margin: 50px 0;
  }

  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 50px 0;

    .loading-text {
      margin-top: 15px;
      color: #888;
    }
  }

  // 卡片网格布局
  .card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 15px;
  }

  // 词库卡片
  .library-card {
    display: flex;
    align-items: flex-start;
    padding: 15px;
    border: 1px solid #e6e6e6;
    border-radius: 8px;
    background: #fff;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    }

    &.card-selected {
      border-color: #409eff;
      background-color: #f0f7ff;
    }

    // 复选框
    .card-checkbox {
      margin-top: 5px;
      margin-right: 12px;
    }

    // 卡片内容
    .card-content {
      display: flex;
      width: 100%;

      // 封面图区域
      .card-cover {
        position: relative;
        width: 80px;
        height: 80px;
        margin-right: 15px;

        .cover-img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 4px;
        }

        // 状态标签
        .status-tag {
          position: absolute;
          bottom: -5px;
          right: -5px;
          z-index: 1;
        }
      }

      // 信息区域
      .card-info {
        flex-grow: 1;
        overflow: hidden;

        .library-name {
          width: 90%;
          font-size: 16px;
          font-weight: 500;
          color: #333;
          margin: 0 0 10px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .info-row {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          margin-bottom: 8px;

          .info-item {
            font-size: 12px;
            color: #666;
            display: flex;
            align-items: center;
            gap: 4px;

            i {
              font-size: 14px;
            }
          }

          .info-item-last:hover {
            color: #409eff;
          }
        }
      }
    }
  }
}

// 分页区域
.pagination-bar {
  margin-top: 20px;
  text-align: right;
}

// 底部按钮区域
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.card-body {
  margin-bottom: 20px;
}

.word-select {
  ::v-deep .el-dialog__body {
    padding: 0 20px !important;
  }
}
</style>
